import base64
import json
import time
import os
from urllib.parse import quote
import requests
import urllib
from django.core.files.storage import default_storage
from django.core.files.base import ContentFile

API_KEY = "6ESlg6Ex4xcVAC4djb4BJC0s"
SECRET_KEY = "ra4gnm3zL3Q69v356jqMuBimajYsXW0p"
APP_ID = '119827610'


class Baidu():
    def __init__(self):
        self.API_KEY = API_KEY
        self.SECRET_KEY = SECRET_KEY
        self.APP_ID = APP_ID

    def get_access_token(self):
        # 先获取token
        url = "https://aip.baidubce.com/oauth/2.0/token"
        params = {"grant_type": "client_credentials", "client_id": self.API_KEY, "client_secret": self.SECRET_KEY}
        return str(requests.post(url, params=params).json().get("access_token"))

    def idcard(self,image_path):   # 身份证识别
        token = self.get_access_token()
        # 有token了之后访问百度api开始验证
        url = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token=" + token
        
        # 判断是URL还是base64图片
        if image_path.startswith('http'):
            # 如果是URL，使用url参数
            # 清理URL，移除可能的空格和特殊字符
            clean_url = image_path.strip()
            print(f"原始URL: {image_path}")
            print(f"清理后URL: {clean_url}")
            
            payload = {
                'id_card_side': 'front',
                'url': clean_url,
                'detect_ps': 'false',
                'detect_risk': 'false',
                'detect_quality': 'false',
                'detect_photo': 'false',
                'detect_card': 'false',
                'detect_direction': 'false'
            }
        else:
            # 如果是base64，使用image参数
            payload = {
                'id_card_side': 'front',
                'image': image_path,
                'detect_ps': 'false',
                'detect_risk': 'false',
                'detect_quality': 'false',
                'detect_photo': 'false',
                'detect_card': 'false',
                'detect_direction': 'false'
            }
        
        headers = {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Accept': 'application/json'
        }

        # 使用urllib.parse.urlencode来正确编码参数
        import urllib.parse
        encoded_data = urllib.parse.urlencode(payload)
        print(f"编码后的参数: {encoded_data}")

        # 发起请求
        response = requests.post(url, headers=headers, data=encoded_data)
        data = json.loads(response.text)
        print(f"百度API响应: {data}")
        
        if data.get("image_status") == "normal" and "words_result" in data:
            word_result = data.get("words_result", {})
            name = word_result.get("姓名", {}).get("words", "")
            idcard = word_result.get("公民身份号码", {}).get("words", "")
            print(f"识别成功 - 姓名: {name}, 身份证号: {idcard}")
            return {'success': True, "name": name, "idcard": idcard}
        else:
            # 如果有error_code，则显示具体的错误信息
            error_msg = data.get("error_msg", "未知错误")
            if data.get("error_code"):
                error_msg = f"错误码: {data.get('error_code')}, 错误信息: {error_msg}"
            print(f"百度API错误: {error_msg}")
            return {'success': False, "message": f'识别出错: {error_msg}'}


baidu = Baidu()


